//
//  SuggestionAndComplainAddVC.m
//  运营管理系统
//
//  Created by 杨毅 on 17/2/20.
//  Copyright © 2017年 杨毅. All rights reserved.
//

#import "SuggestionAndComplainAddVC.h"

@interface SuggestionAndComplainAddVC ()
{
    UIScrollView *_scrollview;
    NSInteger uptypetag;//投诉or建议tag
    NSInteger questionTypeID;//问题类型id
    NSDictionary *_prame;//上交参数
    NSInteger userID;
}
@property (nonatomic,strong)SuggestionView *sugView;
@property (nonatomic,strong)NSMutableArray *typeNameArray;
@property (nonatomic,strong)NSMutableArray *typeIDArray;
@property (nonatomic,strong)HideNameOrShowPopView *namePopview;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation SuggestionAndComplainAddVC
- (AFHTTPSessionManager *)manager{
    
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (NSString *)filePath{
    NSString *documentFilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filetPath = [documentFilePath stringByAppendingPathComponent:@"Log.txt"];
    return filetPath;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"工作建议";
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    NSDictionary *userDic = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
    userID = [[userDic objectForKey:@"userid"]integerValue];
    uptypetag = 1;
    _typeNameArray = [[NSMutableArray alloc]init];
    _typeIDArray = [[NSMutableArray alloc]init];
    
    _scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
    [self.view addSubview:_scrollview];
    UIImageView *topImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_complain"]];
    topImageView.frame = CGRectMake(10, 6, kSCREEN_WIDTH-20, (kSCREEN_WIDTH-20)*0.66);
    [_scrollview addSubview:topImageView];
    
    self.sugView = [[SuggestionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(topImageView.frame)+5, kSCREEN_WIDTH, 320)];
    self.sugView.delegate = self;
    [_scrollview addSubview:self.sugView];
    
    _scrollview.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(self.sugView.frame)+20);
    [self questionTypeNetworking];


    
    //响应者  responder
    //第一响应者  first responder 用户正在操作的控件
    //如果文本框称为第一响应者,则系统会自动弹出键盘
    //如果想要隐藏键盘,只需要放弃第一响应者即可
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    
    [tap addTarget:self action:@selector(hideKeyboard)];
    
    [self.view addGestureRecognizer:tap];
}
- (void)hideKeyboard{
    
    [self.sugView.DiscribTextView resignFirstResponder];
    [self.sugView.QuestionTitleTF resignFirstResponder];
}
/*问题类型接口*/
- (void)questionTypeNetworking{
    
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:QuestionTypeURL parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        SuggesDataModel *datamodel = [[SuggesDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (SuggesAspectModel *model in datamodel.aspect) {
            
            [_typeNameArray addObject:model.aspectName];
            [_typeIDArray addObject:[NSString stringWithFormat:@"%ld",model.aspectId]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
#pragma mark-->suggestionViewDelegate
- (void)UpType:(UIButton *)sender andTag:(NSInteger)typetag{
    //投诉还是建议 提交类型状态
    uptypetag = typetag;
    NSSLog(@"%ld",uptypetag);

}
/*选择问题类型代理方法*/
- (void)ChooseQuestionType:(UIButton *)sender{
    
    if (_typeNameArray != nil) {
        
        MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:_typeNameArray];
        __weak typeof(self) weakSelf = self;
        [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
            [weakSelf.sugView.QuestionBtn setTitle:[NSString stringWithFormat:@"  %@",title] forState:UIControlStateNormal];
            [weakSelf.sugView.QuestionBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
            questionTypeID = [_typeIDArray[index]integerValue];
        }];

    }else{
    
    }
}
- (void)SuggestionViewSubmitClick:(UIButton *)sender{
    
    if ([_sugView.QuestionBtn.titleLabel.text isEqualToString:@"  问题类型"] ||_sugView.QuestionTitleTF.text.length < 1 || _sugView.DiscribTextView.text.length < 1) {
        
        [self showAlert:@"温馨提示" message:@"请完善提交信息" actionWithTitle:@"好的"];
        
    }else{
        
    _sugView.submitBTN.userInteractionEnabled = NO;
    _sugView.CancelBtn.userInteractionEnabled = NO;
    _namePopview = [[HideNameOrShowPopView alloc]initWithFrame:CGRectMake(0, kSCREEN_HEIGHT, 245, 125)];
    _namePopview.delegate = self;
        [_scrollview addSubview:_namePopview];
    }

}
- (void)SuggestionViewCancelClick:(UIButton *)sender{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您是否确定退出当前页面" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:OkAction];
    [self presentViewController:alert animated:YES completion:nil];

}
#pragma mark-->HideNameOrShowPopViewDelegate
- (void)OKBtnClick:(UIButton *)sender andTag:(NSInteger)tag{
//tag匿名or实名

    _sugView.submitBTN.userInteractionEnabled = YES;
    _sugView.CancelBtn.userInteractionEnabled = YES;
    [self dismissHideNameView];
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *timeStr = [dateFormatter stringFromDate:currentDate];
    _prame = @{@"userId":[NSString stringWithFormat:@"%ld",userID],@"aspectOn":[NSString stringWithFormat:@"%ld",questionTypeID],@"type":[NSString stringWithFormat:@"%ld",uptypetag],@"submitTime":timeStr,@"suggestion":self.sugView.DiscribTextView.text,@"anonymity":[NSString stringWithFormat:@"%ld",tag],@"title":self.sugView.QuestionTitleTF.text};

    [self updataNetworking:_prame];
}
- (void)CancelClick:(UIButton *)sender andTag:(NSInteger)tag
{

    [self dismissHideNameView];
    _sugView.submitBTN.userInteractionEnabled = YES;
    _sugView.CancelBtn.userInteractionEnabled = YES;
}
- (void)dismissHideNameView{
    
    [_namePopview removeFromSuperview];
}

//建议或者投诉提交接口
- (void)updataNetworking:(NSDictionary *)prameter{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"提交中...";
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:SuggesAndComplainUpURL parameters:prameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([dic[@"status"]integerValue] == 1) {
            
            //延时操作
            [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"提交成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                
            } completion:^(BOOL finished) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            
            [self showAlert:@"提交失败" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500 || status == 0) {
            [self showAlert:@"提交失败" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"提交失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
}

#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
